#!/usr/bin/env bash

set -e
set -o pipefail

function main() {
    username=$1
    password=$2
    swr_username=$3
    swr_password=$4
    image_version=$5
    big_version=$6

    if [ -d "manifest" ]; then
        echo "删除目录: manifest"
        rm -r "manifest"
    fi

    git clone https://gitcode.com/openUBMC/manifest.git
    cd manifest || exit
    wget -q https://repo.openubmc.cn/"${big_version}"/sdk/bmc_sdk.zip
    python3 build_image.py -s "bmc_sdk.zip" -u "${username}" -p "${password}" -t openubmc/ubuntu:"${image_version}"
    docker tag openubmc/ubuntu:"${image_version}" swr.cn-north-4.myhuaweicloud.com/openubmc/ubuntu:"${image_version}"

    docker login -u "${swr_username}" -p "${swr_password}" swr.cn-north-4.myhuaweicloud.com
    docker push swr.cn-north-4.myhuaweicloud.com/openubmc/ubuntu:"${image_version}"
    docker rmi swr.cn-north-4.myhuaweicloud.com/openubmc/ubuntu:"${image_version}"
    docker rmi openubmc/ubuntu:"${image_version}"
}

usage() {
  cat << EOF
用法: $0 [-u conan_username] [-p conan_password] [-s swr_username] [-w swr_password] [-v image_version] [-b openubmc_version]"
选项：
  -u: the username of conan,
  -p: the password of conan;
  -s: the username of swr repository,
  -w: the password of swr repository;
  -v: the version of image;
  -b: the big version of bmc openUBMC;
EOF
}

validate_not_empty() {
    value="$1"
    name="$2"
    if [ -z "$value" ]; then
        echo "错误: $name 不能为空" >&2
        usage
        return 1
    fi
    return 0
}

while getopts ":u:p:s:w:v:b:h:" opt
do
    case $opt in
        u)
            CONAN_USERNAME="$OPTARG"
            ;;
        p)
            CONAN_PASSWORD="$OPTARG"
            ;;
        s)
            SWR_USERNAME="$OPTARG"
            ;;
        w)
            SWR_PASSWORD="$OPTARG"
            ;;
        v)
            IMAGE_VERSION="$OPTARG"
            ;;
        b)
            BIG_VERSION="$OPTARG"
            ;;
        h)
            usage
            exit 1
            ;;
        \?)
            echo "无效选项: -$OPTARG" >&2
            usage
            exit 1
            ;;
        :)
            echo "选项 -$OPTARG 需要一个参数" >&2
            usage
            exit 1
            ;;
    esac
done


validate_not_empty "${CONAN_USERNAME}" "-u参数" || exit 1
validate_not_empty "${CONAN_PASSWORD}" "-p参数" || exit 1
validate_not_empty "${SWR_USERNAME}" "-s参数" || exit 1
validate_not_empty "${SWR_PASSWORD}" "-w参数" || exit 1
validate_not_empty "${BIG_VERSION}" "-b参数" || exit 1
validate_not_empty "${IMAGE_VERSION}" "-v参数" || exit 1

echo "-------------------start to build docker images-------------------"
main "${CONAN_USERNAME}" "${CONAN_PASSWORD}" "${SWR_USERNAME}" "${SWR_PASSWORD}" "${IMAGE_VERSION}" "${BIG_VERSION}"

exit 0